package com.xmutca.sso.server.filter;

import com.xmutca.core.common.Result;
import com.xmutca.sso.common.Principal;
import com.xmutca.sso.common.util.ShiroWebUtils;
import com.xmutca.sso.server.token.UsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {

	private String redirectUrlParamName = "redirectUrl";

	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String redirectUrl = getRedirectUrl(request);
		boolean xmlHttpRequest = getXmlHttpRequest(request);

		if (StringUtils.isEmpty(password)) {
			password = "";
		}

		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		return new UsernamePasswordToken(username, password, rememberMe, host, redirectUrl, xmlHttpRequest);
	}

	/**
	 * 登陆成功后的处理
	 * @param authenticationToken
	 * @param subject
	 * @param request
	 * @param response
	 * @return
     * @throws Exception
     */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken authenticationToken, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

		//在ajax情况下的处理
		Boolean xmlHttpRequest = (Boolean) subject.getSession().getAttribute("xmlHttpRequest");
		if (xmlHttpRequest.booleanValue()) {
			Result<Object> data = new Result<>(Result.Status.SUCCESS, "login success!", subject.getPrincipal());
			ShiroWebUtils.writeJSONString((HttpServletResponse) response, data);
			return false;
		}

		//非ajax情况下的处理
		if(StringUtils.hasText(usernamePasswordToken.getRedirectUrl())) {
			ShiroWebUtils.redirectToSavedRequestForCustomerRedirectUri(request, response, usernamePasswordToken.getRedirectUrl());
			return false;
		}
		return super.onLoginSuccess(authenticationToken, subject, request, response);
	}

	/**
	 * 获取返回的URI
	 * @param request
	 * @return
     */
	public String getRedirectUrl(ServletRequest request) {
		return WebUtils.getCleanParam(request, redirectUrlParamName);
	}

	/**
	 * 获取请求类型，是否为ajax请求
	 * @param request
	 * @return
     */
	public boolean getXmlHttpRequest(ServletRequest request) {
		return Boolean.TRUE.toString().equals(WebUtils.getCleanParam(request, "xmlHttpRequest"));
	}

	public void setRedirectUrlParamName(String redirectUrlParamName) {
		this.redirectUrlParamName = redirectUrlParamName;
	}
}